// ==UserScript==
// @name         COLLEGES自动识别验证码
// @namespace    your_namespace
// @version      1.1
// @description  COLLEGES自动识别验证码填写
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// ==/UserScript==
(function() {
    'use strict';
    
    const API_URL = 'https://api.nonex.top/captcha/code';

    function init() {
        const captchaInput = document.getElementById('captchatext');
        const captchaImage = document.getElementById('captcha');
        
        if (!captchaInput || !captchaImage) {
            setTimeout(init, 500); // 轮询直到元素加载
            return;
        }

        captchaInput.addEventListener('focus', async function() {
            const base64Data = captchaImage.src.split(',')[1] || '';
            
            GM_xmlhttpRequest({
                method: "POST",
                url: API_URL,
                headers: {
                    "Content-Type": "application/json",
                    "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0"
                },
                data: JSON.stringify({ ImageBase64: base64Data }),
                onload: function(response) {
                    try {
                        const result = JSON.parse(response.responseText);
                        if (result.status === 'success') {
                            const inputEvent = new Event('input', { 
                                bubbles: true,
                                cancelable: true
                            });
                            captchaInput.value = result.result;
                            captchaInput.dispatchEvent(inputEvent);
                            
                            // 触发验证事件
                            const verifyEvent = new Event('change');
                            captchaInput.dispatchEvent(verifyEvent);
                        }
                    } catch (e) {
                        console.error('验证码识别失败:', e);
                    }
                }
            });
        });
    }

    // 兼容不同加载状态的初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();